package com.atom.common.util;

import org.activiti.engine.impl.util.json.JSONException;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.atom.common.exception.AvensIllegalArgumentException;
import com.atom.common.exception.AvensJsonResultParserException;

public class JsonResultParser {

  private static Logger logger = Logger.getLogger(JsonResultParser.class); 

  public static void parse(String result) {      
    logger.info("JsonResultParser result : " + result);
    JSONObject jsonObject = new JSONObject();
    String status;
    try {
      jsonObject = new JSONObject(result);  
      status = jsonObject.getString("status");
    } catch (JSONException e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensJsonResultParserException("JsonResultParser result is not a legal result");
    }

    if (StringUtils.equals("OK", status) || StringUtils.equals("ok", status)) {
      return;
    } else {
      throw new AvensJsonResultParserException("JsonResultParser result is not OK");
    }

  }



  public static String getData(String result) {
    logger.info("JsonResultParser result : " + result);
    JSONObject jsonObject = new JSONObject();
    String status;
    String data;
    try {
      jsonObject = new JSONObject(result);  
      status = jsonObject.getString("status");
      data = jsonObject.getString("data");
    } catch (JSONException e) {
      logger.error("error message = {}" + e.getMessage(), e);
      throw new AvensIllegalArgumentException("JsonResultParser result is not a legal result");
    }

    if (StringUtils.equals("OK", status) || StringUtils.equals("ok", status)) {
      return data;
    } else {
      throw new AvensJsonResultParserException("Operation Failed!");
    }
  }
  
  public static Object getValueFromData(String result, String key) {
    JSONObject json = new JSONObject(result);
    String status = json.getString("status");
    Object value = null;
    if (StringUtils.equals("OK", status) || StringUtils.equals("ok", status)) {
      JSONObject data = json.getJSONObject("data");
      value = data.get(key);
    }
    return value;
  }
  

}
